#!/bin/bash
# ========================================
# RedFire数据库系统初始化总脚本
# 版本: v5.0.0 (2025-09-16)
# 功能: 统一初始化和健康检查
# ========================================

set -e

echo "=========================================="
echo "开始RedFire数据库系统初始化..."
echo "时间: $(date)"
echo "=========================================="

# 设置日志文件
LOG_FILE="/logs/init-$(date +%Y%m%d_%H%M%S).log"
exec 1> >(tee -a "$LOG_FILE")
exec 2> >(tee -a "$LOG_FILE" >&2)

# 设置默认值
MYSQL_HOST=${MYSQL_HOST:-mysql-business}
MYSQL_USER=${MYSQL_USER:-root}
MYSQL_PASSWORD=${MYSQL_PASSWORD:-redfire_root_2025}

POSTGRES_HOST=${POSTGRES_HOST:-postgresql-analytics}
POSTGRES_USER=${POSTGRES_USER:-redfire_analytics}
POSTGRES_PASSWORD=${POSTGRES_PASSWORD:-redfire_pg_2025}

REDIS_HOST=${REDIS_HOST:-redis}
REDIS_PASSWORD=${REDIS_PASSWORD:-redfire_redis_2025}

# 等待服务启动函数
wait_for_service() {
    local host=$1
    local port=$2
    local service_name=$3
    local max_attempts=60
    local attempt=1
    
    echo "等待 $service_name 服务启动 ($host:$port)..."
    
    while [ $attempt -le $max_attempts ]; do
        if nc -z "$host" "$port" 2>/dev/null; then
            echo "$service_name 服务已启动！"
            return 0
        fi
        
        echo "尝试 $attempt/$max_attempts: $service_name 未就绪，等待中..."
        sleep 2
        attempt=$((attempt + 1))
    done
    
    echo "错误: $service_name 服务启动超时"
    return 1
}

# MySQL健康检查函数
check_mysql() {
    echo "检查MySQL连接..."
    if mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -e "SELECT 1;" >/dev/null 2>&1; then
        echo "MySQL连接成功！"
        return 0
    else
        echo "MySQL连接失败！"
        return 1
    fi
}

# PostgreSQL健康检查函数
check_postgresql() {
    echo "检查PostgreSQL连接..."
    if PGPASSWORD="$POSTGRES_PASSWORD" psql -h "$POSTGRES_HOST" -U "$POSTGRES_USER" -d "redfire_analytics" -c "SELECT 1;" >/dev/null 2>&1; then
        echo "PostgreSQL连接成功！"
        return 0
    else
        echo "PostgreSQL连接失败！"
        return 1
    fi
}

# Redis健康检查函数
check_redis() {
    echo "检查Redis连接..."
    if redis-cli -h "$REDIS_HOST" -a "$REDIS_PASSWORD" ping >/dev/null 2>&1; then
        echo "Redis连接成功！"
        return 0
    else
        echo "Redis连接失败！"
        return 1
    fi
}

# 数据库状态检查函数
check_database_status() {
    local db_type=$1
    local host=$2
    local user=$3
    local password=$4
    local database=$5
    
    echo "检查 $db_type 数据库状态..."
    
    case $db_type in
        "mysql")
            mysql -h "$host" -u "$user" -p"$password" -e "
                SELECT 
                    'Database Status' as info_type,
                    'MySQL' as database_type,
                    VERSION() as version,
                    NOW() as current_time,
                    @@hostname as hostname;
                
                SELECT 
                    'Connection Info' as info_type,
                    COUNT(*) as total_connections,
                    SUM(CASE WHEN COMMAND = 'Sleep' THEN 1 ELSE 0 END) as idle_connections,
                    SUM(CASE WHEN COMMAND != 'Sleep' THEN 1 ELSE 0 END) as active_connections
                FROM information_schema.PROCESSLIST;
                
                SELECT 
                    'Database Size' as info_type,
                    SCHEMA_NAME as database_name,
                    ROUND(SUM(DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024, 2) as size_mb
                FROM information_schema.SCHEMATA s
                LEFT JOIN information_schema.TABLES t ON s.SCHEMA_NAME = t.TABLE_SCHEMA
                WHERE s.SCHEMA_NAME IN ('redfire_trading')
                GROUP BY s.SCHEMA_NAME;
            " 2>/dev/null || echo "$db_type 状态检查失败"
            ;;
            
        "postgresql")
            PGPASSWORD="$password" psql -h "$host" -U "$user" -d "$database" -c "
                SELECT 
                    'Database Status' as info_type,
                    'PostgreSQL' as database_type,
                    version() as version,
                    current_timestamp as current_time,
                    inet_server_addr() as server_addr;
                
                SELECT 
                    'Connection Info' as info_type,
                    count(*) as total_connections,
                    count(*) FILTER (WHERE state = 'idle') as idle_connections,
                    count(*) FILTER (WHERE state = 'active') as active_connections
                FROM pg_stat_activity;
                
                SELECT 
                    'Database Size' as info_type,
                    current_database() as database_name,
                    pg_size_pretty(pg_database_size(current_database())) as size;
                
                SELECT 
                    'Extensions' as info_type,
                    extname as extension_name,
                    extversion as version
                FROM pg_extension
                WHERE extname IN ('timescaledb', 'pg_stat_statements', 'uuid-ossp')
                ORDER BY extname;
            " 2>/dev/null || echo "$db_type 状态检查失败"
            ;;
    esac
}

# 主初始化流程
main() {
    echo "开始服务等待和健康检查..."
    
    # 等待各服务启动
    wait_for_service "$MYSQL_HOST" 3306 "MySQL" || exit 1
    wait_for_service "$POSTGRES_HOST" 5432 "PostgreSQL" || exit 1
    wait_for_service "$REDIS_HOST" 6379 "Redis" || exit 1
    
    echo ""
    echo "=========================================="
    echo "服务连接测试"
    echo "=========================================="
    
    # 连接测试
    check_mysql || exit 1
    check_postgresql || exit 1
    check_redis || exit 1
    
    echo ""
    echo "=========================================="
    echo "数据库状态检查"
    echo "=========================================="
    
    # 数据库状态检查
    check_database_status "mysql" "$MYSQL_HOST" "$MYSQL_USER" "$MYSQL_PASSWORD" "redfire_trading"
    echo ""
    check_database_status "postgresql" "$POSTGRES_HOST" "$POSTGRES_USER" "$POSTGRES_PASSWORD" "redfire_analytics"
    
    echo ""
    echo "=========================================="
    echo "Redis状态检查"
    echo "=========================================="
    
    # Redis状态检查
    redis-cli -h "$REDIS_HOST" -a "$REDIS_PASSWORD" INFO server | grep -E "redis_version|os|arch|process_id|uptime_in_seconds" || true
    redis-cli -h "$REDIS_HOST" -a "$REDIS_PASSWORD" INFO memory | grep -E "used_memory_human|used_memory_peak_human|maxmemory_human" || true
    redis-cli -h "$REDIS_HOST" -a "$REDIS_PASSWORD" INFO stats | grep -E "total_connections_received|total_commands_processed|keyspace_hits|keyspace_misses" || true
    
    echo ""
    echo "=========================================="
    echo "系统资源检查"
    echo "=========================================="
    
    # 系统资源检查
    echo "主机信息:"
    echo "  - 主机名: $(hostname)"
    echo "  - 系统时间: $(date)"
    echo "  - 系统负载: $(uptime | awk -F'load average:' '{print $2}')"
    
    if command -v free >/dev/null 2>&1; then
        echo "内存使用:"
        free -h
    fi
    
    if command -v df >/dev/null 2>&1; then
        echo "磁盘使用:"
        df -h | grep -E "^/dev|^Filesystem"
    fi
    
    echo ""
    echo "=========================================="
    echo "网络连接测试"
    echo "=========================================="
    
    # 测试各服务间网络连接
    echo "网络连接测试:"
    echo "  - MySQL ($MYSQL_HOST:3306): $(nc -z $MYSQL_HOST 3306 && echo '✓ 连通' || echo '✗ 失败')"
    echo "  - PostgreSQL ($POSTGRES_HOST:5432): $(nc -z $POSTGRES_HOST 5432 && echo '✓ 连通' || echo '✗ 失败')"
    echo "  - Redis ($REDIS_HOST:6379): $(nc -z $REDIS_HOST 6379 && echo '✓ 连通' || echo '✗ 失败')"
    
    echo ""
    echo "=========================================="
    echo "初始化完成总结"
    echo "=========================================="
    
    echo "✓ RedFire数据库系统初始化完成！"
    echo "✓ 所有服务连接正常"
    echo "✓ 数据库状态健康"
    echo "✓ 系统资源充足"
    echo ""
    echo "服务访问信息:"
    echo "  - MySQL业务数据库: $MYSQL_HOST:3306"
    echo "  - PostgreSQL分析数据库: $POSTGRES_HOST:5432"
    echo "  - Redis缓存: $REDIS_HOST:6379"
    echo ""
    echo "管理工具访问:"
    echo "  - phpMyAdmin: http://localhost:8080"
    echo "  - pgAdmin: http://localhost:8081"
    echo "  - Redis Commander: http://localhost:8082"
    echo "  - Grafana监控: http://localhost:3000"
    echo "  - Prometheus: http://localhost:9090"
    echo ""
    echo "日志文件: $LOG_FILE"
    echo "初始化时间: $(date)"
    echo "=========================================="
}

# 错误处理
trap 'echo "初始化过程中发生错误，请检查日志: $LOG_FILE"; exit 1' ERR

# 执行主函数
main

echo "初始化脚本执行完成，容器将退出。"
